package main

import (
	"d-blog/db"
	"d-blog/model"
	"d-blog/scheduler"
	"d-blog/service"
	"encoding/json"
	"fmt"
	"github.com/julienschmidt/httprouter"
	"github.com/kataras/iris/v12"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
)

func index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	log.Printf("你好啊，%s", "赵东潮")
	id := service.TipService.GetById("4294053921503673")
	fmt.Println(id)
	data, _ := json.Marshal(id)
	w.Write(data)
}

// 定义mysql账号密码等信息
const (
	USERNAME     = "root"
	PASSWORD     = "Aa1234567890..."
	NETWORK      = "tcp"
	SERVER       = "47.117.69.119"
	PORT         = 3306
	DatabaseName = "aimeizi"
)

func main() {
	scheduler.Start()
	// 连接数据库
	dsn := fmt.Sprintf("%s:%s@%s(%s:%d)/%s", USERNAME, PASSWORD, NETWORK, SERVER, PORT, DatabaseName)
	if err := db.OpenDB(dsn+"?charset=utf8&parseTime=True&loc=Local", &gorm.Config{}, 10, 20, model.Models...); err != nil {
		logrus.Error(err)
	}

	application := iris.New()
	application.Logger().SetLevel("debug")
	application.Any("/", func(context iris.Context) {
		_, _ = context.HTML("<h1>Powered by zhaodongchao</h1>")
	})
	//http服务原始api
	server := &http.Server{Addr: ":8081"}
	//监听系统停机指令
	handleSignal(server)
	//使用iris构建web服务
	err := application.Run(iris.Server(server), iris.WithConfiguration(iris.Configuration{
		DisableStartupLog:                 false,
		DisableInterruptHandler:           false,
		DisablePathCorrection:             false,
		EnablePathEscape:                  false,
		FireMethodNotAllowed:              false,
		DisableBodyConsumptionOnUnmarshal: false,
		DisableAutoFireStatusCode:         false,
		EnableOptimizations:               true,
		TimeFormat:                        "2006-01-02 15:04:05",
		Charset:                           "UTF-8",
	}))
	if nil != err {
		logrus.Error(err)
		os.Exit(-1)
	}

}

func init() {
	log.Println("系统开始启动...")
}

func handleSignal(server *http.Server) {
	c := make(chan os.Signal)
	signal.Notify(c, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTERM)

	go func() {
		s := <-c
		logrus.Infof("got signal [%s], exiting now", s)
		if err := server.Close(); nil != err {
			logrus.Errorf("server close failed: " + err.Error())
		}

		// 关闭数据连接
		db.CloseDB()

		logrus.Infof("Exited")
		os.Exit(0)
	}()
}
